<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="文件名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select ref="focusElemnt" v-model="listQuery.type" placeholder="作业名称(必选)" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in type.list" :key="item.oid" :label="item.title" :value="item.oid" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        发送邮件
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        打包下载
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="handleSave">
        保存操作
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交日期" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.modified | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件名" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleDownloadSimgle(row)">{{ row.title }}</span>
          <el-tag>{{ row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上传者" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleDownloadSimgle(row)">
            下载
          </el-button>
          <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            Publish
          </el-button>
          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">
            Draft
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleModifyStatus(row,'deleted')">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="emailRules" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="邮箱地址" prop="address">
          <el-input v-model="temp.address" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="sendEmail()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchFiles, packAndSendEmail, saveFileOption, downloadFile, downloadZip } from '@/api/file'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { saveAs } from 'file-saver'
import { fetchHomework } from '../../api/homework'
import { validEmail } from '@/utils/validate'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('邮箱地址错误'))
      } else {
        callback()
      }
    }
    return {
      dialogTitle: '发送邮件',
      tableKey: 0,
      list: null,
      total: 0,
      type: {
        list: null
      },
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      temp: {
        id: undefined,
        address: 'your emailAddress'
      },
      dialogFormVisible: false,
      dialogPvVisible: false,
      pvData: [],
      emailRules: {
        address: [{ request: true, trigger: 'blur', validator: validateEmail }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getHomework()
  },
  methods: {
    getHomework() {
      fetchHomework(this.listQuery).then(response => {
        this.type.list = response.items
        this.type.total = response.total
      })
    },
    getList() {
      this.listLoading = true
      fetchFiles(this.listQuery).then(response => {
        this.list = response.items
        this.total = response.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    /**
     * 用户设置好 查询条件
     * 进行查询
     */
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    /**
     * 保存对文件的删除操作
     */
    handleSave() {
      this.listLoading = true
      saveFileOption({
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        // 先把item中 状态是deleted的过滤出来
        // 在映射得到 名称 数组
        // 最后还要编码特殊字符 (' ' -> '%20')
        list: encodeURI(this.list.filter(item => {
          return item.status === 'deleted'
        }).map((item, index) => {
          return item.name
        }))
      })
        .then((response) => {
          this.list = response.items
          this.total = response.total
        }, (err) => {
          console.log(err)
        }).finally(() => {
          this.listLoading = false
        })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    checkType() {
      if (this.listQuery.type === undefined) {
        this.$notify({
          message: '请先选择操作那次作业',
          type: 'error',
          duration: 2000
        })
        this.$refs.focusElemnt.focus()
        return false
      }
      return true
    },
    handleCreate() {
      if (!this.checkType()) { return }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    sendEmail() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          packAndSendEmail({
            address: this.temp.address,
            type: this.listQuery.type
          }).then((res) => {
            this.$notify({
              title: 'Success',
              message: '发送成功',
              type: 'success',
              duration: 2000
            })
          }, (err) => {
            console.log(err)
            this.$notify({
              title: 'Fail',
              message: '发送失败',
              type: 'fail',
              duration: 2000
            })
          })

          this.dialogFormVisible = false
        }
      })
    },
    // 下载单次文件
    handleDownloadSimgle(row) {
      downloadFile({ fileName: row.name })
        .then((res) => {
          saveAs(res, row.name)
        }, (err) => {
          console.log(err)
          this.$message('下载失败')
        })
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    // 下载整次作业zip
    handleDownload() {
      if (!this.checkType()) { return }
      this.downloadLoading = true
      downloadZip({
        type: this.listQuery.type
      })
        .then((res) => {
          let fname = this.listQuery.type
          if (!fname) {
            fname = 'upload.zip'
          } else {
            fname = fname + '.zip'
          }
          saveAs(res, fname)
          this.downloadLoading = false
        }, (err) => {
          console.log(err)
          this.downloadLoading = false
          this.$message('下载失败')
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
